﻿using System;
using System.Data;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Ledict.ConditionExtract.Base;
using Ledict.ConditionExtract.BLL;
using Ledict.ConditionExtract.Common;
using Ledict.ConditionExtract.Controls;

namespace Ledict.ConditionExtract
{
    /// <summary>
    /// 基础词库
    /// </summary>
    public partial class WB_Manage_Base : BaseForm
    {
        #region 构造初始
        private static WB_Manage_Base _default;
        private static readonly object _lock = new object();

        private string EditWB_ID = "";
        //private string EditWBS_ID = "";
        //private string EditWBS_SynonymWords = "";


        private readonly WordBankBLL _wordbankbll = new WordBankBLL();
        private readonly WordBankKeyWordsBLL _wordbankkeywordsbll = new WordBankKeyWordsBLL();
        //private WordBankSynonymBLL wordbanksynonymbll = new WordBankSynonymBLL();

        public WB_Manage_Base()
        {
            InitializeComponent();
        }

        public static WB_Manage_Base Default
        {
            get
            {
                if (_default == null || _default.IsDisposed)
                {
                    lock (_lock)
                    {
                        if (_default == null || _default.IsDisposed)
                        {
                            _default = new WB_Manage_Base();
                        }
                    }
                }
                return _default;
            }
        }
        #endregion


        private void WB_Manage_Base_Load(object sender, EventArgs e)
        {
            ShowWordBank();
        }

        #region 词库左侧

        /// <summary>
        ///     显示
        /// </summary>
        public void ShowWordBank()
        {
            dataPagerMain.ChangePageNumber(1);
        }

        /// <summary>
        ///     显示（下一页）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataPagerMain_PageNumberChanging(object sender, DataPagerPageIndexChangingEventArgs e)
        {
            var startRowIndex = e.StartRowIndex;
            //var maximumRows = e.MaximumRows;
            var endRowIndex = e.StartRowIndex + e.MaximumRows;
            var dt = _wordbankbll.GetList();

            if (dt.Rows.Count > 0)
            {
                e.TotalCount = dt.Rows.Count;

                var newdt = new DataTable();
                newdt = dt.Clone();
                var dr = dt.Select("showindex>" + startRowIndex + " and showindex<=" + endRowIndex);
                for (var i = 0; i < dr.Length; i++)
                {
                    newdt.ImportRow(dr[i]);
                }

                GV_WordBook.DataSource = newdt;
            }
            else
            {
                GV_WordBook.DataSource = new DataTable();
            }
        }

        /// <summary>
        ///     添加词库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Add_Click(object sender, EventArgs e)
        {
            var dialogAddwordbook = new WB_AddWordBook();
            dialogAddwordbook.Show();
        }


        /// <summary>
        ///     删除词库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Delete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(@"确认要删除数据吗？", @"此删除不可恢复", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    for (var i = 0; i <= GV_WordBook.Rows.Count - 1; i++)
                    {
                        var check = (DataGridViewCheckBoxCell)GV_WordBook.Rows[i].Cells["Column1"];
                        if (Convert.ToBoolean(check.Value))
                        {
                            var deleteIrId = GV_WordBook.Rows[i].Cells["WB_ID"].Value.ToString();
                            if (deleteIrId != "")
                            {
                                _wordbankbll.Delete(deleteIrId);
                            }
                        }
                    }
                    MessageBox.Show("删除成功!");
                }
                catch (Exception error)
                {
                    MessageBox.Show("删除失败!");
                    Log.ErrorLog(error.Message);
                }
                ShowWordBank();
            }
        }

        /// <summary>
        ///     修改词库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Update_Click(object sender, EventArgs e)
        {
          
            var dialogAddwordbook = new WB_AddWordBook();
            for (var i = 0; i <= GV_WordBook.Rows.Count - 1; i++)
            {
                var check = (DataGridViewCheckBoxCell)GV_WordBook.Rows[i].Cells["Column1"];
                if (Convert.ToBoolean(check.Value))
                {
                    dialogAddwordbook.publicWB_ID = GV_WordBook.Rows[i].Cells["WB_ID"].Value.ToString();
                    dialogAddwordbook.publicWB_Name = GV_WordBook.Rows[i].Cells["WB_Name"].Value.ToString();
                    dialogAddwordbook.publicHeadWordId = GV_WordBook.Rows[i].Cells["HeadWordIds"].Value.ToString();
                    break;
                }
            }
            if (!string.IsNullOrEmpty(dialogAddwordbook.publicWB_Name))
            {
                dialogAddwordbook.Show();
            }
        }

        #endregion

        #region 词库右侧

        private void GV_WordBook_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            // int WB_ID = GV_WordBook.Rows[i].Cells["WB_ID"].Value.ToString();
            
            EditWB_ID = GV_WordBook.Rows[e.RowIndex].Cells["WB_ID"].Value.ToString();
            richTextBox1.Text = _wordbankkeywordsbll.GetList_WB_ID(EditWB_ID);
        }

        #region 定位查找

        //当前查询关键字的顺序
        private int NowLocateCount;

        /// <summary>
        ///     功能按钮，在该按钮左侧文本框中输入查询词，点击定位标记选中词库中的第一个结果词，再次点击定位下一个结果词，以此类推，直到定位到最后一个结果词为止；
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LocateWordBtn_Click(object sender, EventArgs e)
        {
            richTextBox1.SelectionStart = 0;
            richTextBox1.SelectionLength = richTextBox1.Text.Length;
            richTextBox1.SelectionBackColor = Color.White;
            MatchCollection mc;
            var r = new System.Text.RegularExpressions.Regex(SelectWord.Text.Trim()); //定义一个Regex对象实例
            mc = r.Matches(richTextBox1.Text);
            if (NowLocateCount < mc.Count)
            {
                var start = mc[NowLocateCount].Index; //记录匹配字符的位置
                var length = (SelectWord.Text.Trim()).Length;
                richTextBox1.SelectionStart = start;
                richTextBox1.SelectionLength = length;
                richTextBox1.SelectionBackColor = Color.Red;
                richTextBox1.ScrollToCaret();
                NowLocateCount++;
            }
        }

        /// <summary>
        ///     查询关键字变化，重新查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelectWord_TextChanged(object sender, EventArgs e)
        {
            NowLocateCount = 0;
        }

        #endregion

        private void EditWBKeyWords_Click(object sender, EventArgs e)
        {
            var wbEditwbkeywords = WB_EditWBKeyWords.Default;
            wbEditwbkeywords.WB_ID = EditWB_ID;
            wbEditwbkeywords.Show();
        }

        #endregion
    }
}